import 'package:auto_route/auto_route.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

@RoutePage(name: 'WebPageRoute')
class WebPage extends StatefulWidget {
  final String url;
  final String title;
  final bool isFullScreen;

  const WebPage({
    super.key,
    required this.url,
    required this.title,
    this.isFullScreen = true,
  });

  @override
  State<WebPage> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  late final WebViewController _controller;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.transparent)
      ..setNavigationDelegate(
        NavigationDelegate(onPageFinished: (_) => _injectHideFooter()),
      )
      ..loadRequest(Uri.parse(widget.url));
  }

  @override
  Widget build(BuildContext context) {
    return widget.isFullScreen ? _buildFullScreen() : _buildEmbedded();
  }

  Widget _buildFullScreen() {
    return Scaffold(
      appBar: CommonAppBar(title: widget.title),
      body: _buildWebView(),
    );
  }

  Widget _buildEmbedded() {
    return Column(children: [Expanded(child: _buildWebView())]);
  }

  Widget _buildWebView() {
    return Container(
      color: Colors.white,
      child: WebViewWidget(controller: _controller),
    );
  }

  Future<void> _injectHideFooter() async {
    const script = """
      try {
        const style = document.createElement('style');
        style.textContent = '.detail-footer { display: none !important; }';
        document.head.appendChild(style);
        document.querySelectorAll('.detail-footer').forEach((el) => el.style.setProperty('display', 'none', 'important'));
      } catch (e) {
        console.log('inject style failed', e);
      }
    """;
    await _controller.runJavaScript(script);
  }
}
